package com.woniuxy.sddfp.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.woniuxy.sddfp.common.constant.redis.RedisConstant;
import com.woniuxy.sddfp.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author yellow Docter
 * @date 2024-11-14
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String sendCode(String phone) {

        String key = RedisConstant.SMS_PREFIX + phone;

        //01 随机验证码
        //02 发送短信  到阿里云
        //03 短信存储到redis
        // 验证码还没有过期，直接返回
        if (stringRedisTemplate.hasKey(key)){
            String redisCode = stringRedisTemplate.opsForValue().get(key);
            return redisCode;
        }
        String code = RandomUtil.randomNumbers(4);
        // 验证码存储到redis
        stringRedisTemplate.opsForValue().set(key,code, Duration.ofMinutes(5));
        // 调用阿里云sms服务，发送验证码
//        smsTemplate.sendSms(phone,code);

        return code;

    }
}
